﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace COFE.Core.Filter
{
    public abstract class EntryFilterBase : IEntryFilter
    {
        protected EntryFilterBase(string value, string id)
        {
            Value = value;
            SupportedMatchType = MatchType.None;
            Negative = id.StartsWith("-");
        }

        public MatchType
            Matches(IInternalFileSystemInfoExA entry,
            params IOptionFilter[] options)
        {
            var retMatchType = matches(entry, options);            

            if (Negative)
            {
                var retVal = MatchType.None;
                if (SupportedMatchType.HasFlag(MatchType.MatchSubEntry) &&
                    !retMatchType.HasFlag(MatchType.MatchSubEntry))
                    retVal |= MatchType.MatchSubEntry;

                if (SupportedMatchType.HasFlag(MatchType.MatchThisEntry) &&
                    !retMatchType.HasFlag(MatchType.MatchThisEntry))
                    retVal |= MatchType.MatchThisEntry;

                return retVal | _unsupportedMatchType;
            }
            else
                return SupportedMatchType & retMatchType | _unsupportedMatchType;
        }

        public abstract MatchType
            matches(IInternalFileSystemInfoExA entry,
            params IOptionFilter[] options);


        private MatchType _supportedMatchType, _unsupportedMatchType;



        public bool Negative { get; protected set; }
        public MatchType SupportedMatchType { get { return _supportedMatchType; }
            set
            {
                _supportedMatchType = value;

                _unsupportedMatchType = MatchType.None;
                foreach (var val in Enum.GetValues(typeof(MatchType)))
                {
                    var mt = (MatchType)val;

                    if (mt != MatchType.All && mt != MatchType.None)
                        if (!_supportedMatchType.HasFlag(mt))
                            _unsupportedMatchType |= mt;
                }
            }
        }
        public string Value { get; protected set; }
        public virtual string Type { get { 
            return (Negative ? "-" : "") + 
                FilterAttribute.GetFilterAttribute(this).FilterName; } }

        public override string ToString()
        {
            return String.Format("{0} = {1}", Type, Value);
        }

    }
}
